package webssl

import (
	"encoding/json"
	"go-web/base"
	"io/ioutil"
	"net/http"
	"os"
	"strings"
	"sync"

)

var (
	_recvMap = make(map[string]bool)
	_mutx sync.Mutex
)

func RunWebSSLServer(crt, key, url string) {
	if _, err := os.Open(crt); err != nil {
		panic(err)
	}
	if _, err := os.Open(key); err != nil {
		panic(err)
	}
	http.HandleFunc("/echo", sslHandler)
	err := http.ListenAndServeTLS(url, crt, key, nil)
	if err != nil {
		panic(err)
	}
}

func sslHandler(w http.ResponseWriter, r *http.Request) {
	base.Dosafe(func() {
		body, err := ioutil.ReadAll(r.Body)
		if err != nil {
			w.Write([]byte(base.Err_ReadDataFail))
			return
		}

		contents := strings.Split(string(body), "\n")
		result := make([]bool, len(contents))
		for i, str := range contents{
			result[i] = _recvMap[str]
			_mutx.Lock()
			if !_recvMap[str] {
				_recvMap[str] = true
			}
			_mutx.Unlock()
		}

		w.Header().Set("Content-Type", "text/plain")
		retJson, err := json.Marshal(result)
		if err != nil {
			w.Write([]byte(base.Err_MarshalFail))
			return
		}
		w.Write(retJson)
	}, nil)

}
